package glossos.tree.snapshot;

import com.google.common.collect.Lists;
import glossos.tree.Node;

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class PersistentNodeMap implements Map<String, Node> {

	private final NodeRepository nodeRepository;
	private final Node owner;
	private List<Node> values;
	private final Comparator<Node> inverseFrequencyComparator = new Comparator<Node>(){
		public int compare(Node o1, Node o2) {
			return -1 * o1.getFrequency().compareTo(o2.getFrequency());
		}
	};

    public PersistentNodeMap(Node owner, NodeRepository nodeRepository) {
        this.owner = owner;
        this.nodeRepository = nodeRepository;
    }
	
    public void clear() {
		// TODO Auto-generated method stub
		
	}

	public boolean containsKey(Object key) {
		return get(key) != null;
	}

	public boolean containsValue(Object value) {
		// TODO Auto-generated method stub
		return false;
	}

	public Set<java.util.Map.Entry<String, Node>> entrySet() {
		// TODO Auto-generated method stub
		return null;
	}

	public Node get(Object key) {
		String word  = (String) key;
		Node node = nodeRepository.findByParentIdAndWord(owner.getId(), word);
		return node;
	}

	public boolean isEmpty() {
		Set<Node> nodes = nodeRepository.findByParentId(owner.getId());
		return nodes.isEmpty();
	}

	public Set<String> keySet() {
		// TODO Auto-generated method stub
		return null;
	}

	public Node put(String word, Node node) {
		if (node == null)
			throw new IllegalArgumentException();
		nodeRepository.save(node);
		return null;
	}

	public void putAll(Map<? extends String, ? extends Node> m) {
		// TODO Auto-generated method stub
		
	}

	public Node remove(Object key) {
		// TODO Auto-generated method stub
		return null;
	}

	public int size() {
		return values.size();
	}

	public synchronized Collection<Node> values() {
		if (values == null){
			values = Lists.newArrayList(nodeRepository.findByParentId(owner.getId()));
			Collections.sort(values, inverseFrequencyComparator);
		}
		return values;
	}

}
